package com.fortune.cat.manager;

import javax.tools.*;
import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhaozeyang
 */
public class FileManager extends ForwardingJavaFileManager<StandardJavaFileManager> {

    protected final Map<String, Output> map = new HashMap<String, Output>();

    public FileManager(JavaCompiler compiler) {
        super(compiler.getStandardFileManager(null, null, null));
    }  //取得文件管理器

    @Override
    public Output getJavaFileForOutput
            (Location location, String name, JavaFileObject.Kind kind, FileObject source) {
        Output mc = new Output(name, kind);
        this.map.put(name, mc);
        return mc;
    }

    public Output getOutput(String name) {
        return map.get(name);
    }

    public static class Output extends SimpleJavaFileObject {
        private final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        public Output(String name, Kind kind) {
            super(URI.create("dynamic:///" + name.replace('.', '/') + kind.extension), kind);
        } //URI

        byte[] toByteArray() {  //外部调用，生成Class
            return this.byteArrayOutputStream.toByteArray();
        }

        @Override
        public ByteArrayOutputStream openOutputStream() {
            return this.byteArrayOutputStream;
        }
    }

    public static class Source extends SimpleJavaFileObject {
        private final String content;

        public Source(String name, Kind kind, String content) {
            super(URI.create("dynamic:///" + name.replace('.', '/') + kind.extension), kind);
            this.content = content;
        }

        @Override
        public CharSequence getCharContent(boolean ignore) {
            return this.content;
        }
    }
}